package com.work.game.ad;

import android.app.Activity;
import android.view.View;
import android.widget.FrameLayout;

import com.bytedance.sdk.openadsdk.AdSlot;
import com.bytedance.sdk.openadsdk.TTAdNative;
import com.bytedance.sdk.openadsdk.TTAdSdk;
import com.bytedance.sdk.openadsdk.TTFeedAd;
import com.bytedance.sdk.openadsdk.TTNativeAd;
import com.bytedance.sdk.openadsdk.mediation.ad.MediationAdSlot;
import com.bytedance.sdk.openadsdk.mediation.ad.MediationExpressRenderListener;
import com.bytedance.sdk.openadsdk.mediation.manager.MediationNativeManager;
import com.work.game.utils.FeedAdUtils;
import com.work.game.utils.UIUtils;

import java.util.List;

import cn.hutool.core.util.ObjectUtil;

/**
 * 信息流广告
 */
public class MediationFeedAd {
    private String codeId;
    private Activity activity;
    private FrameLayout flFeed;
    private TTFeedAd mTTFeedAd; // Feed广告对象

    public MediationFeedAd() {
    }

    public static volatile MediationFeedAd instance;

    public static synchronized MediationFeedAd getInstance() {
        if (ObjectUtil.isNull(instance)) {
            synchronized (MediationFeedAd.class) {
                if (ObjectUtil.isNull(instance)) {
                    instance = new MediationFeedAd();
                }
            }
        }
        return instance;
    }

    public void init(String codeId) {
        this.codeId = codeId;
    }

    public void setActivity(Activity activity) {
        this.activity = activity;
    }

    //加载信息流广告
    public void loadCacheNativeAd() {
        TTAdNative adNativeLoader = TTAdSdk.getAdManager().createAdNative(activity);
        adNativeLoader.loadFeedAd(buildNativeAdslot(), new TTAdNative.FeedAdListener() {
            @Override
            public void onError(int erroCode, String errorMsg) {
                //广告加载失败
                System.out.println(errorMsg);
            }

            @Override
            public void onFeedAdLoad(List<TTFeedAd> list) {
                //广告加载成功
                //信息流广告渲染具体参考demo
                //如果是自渲染下载类广告可以通过以下api获取下载六要素
                if (list != null && list.size() > 0) {
                    mTTFeedAd = list.get(0);
//                    ComplianceInfo complianceInfo = mTTFeedAd.getComplianceInfo();
//                    if (complianceInfo != null) {
//                        String appName = complianceInfo.getAppName(); //应用名称
//                        String appVersion = complianceInfo.getAppVersion(); //应用版本号
//                        String developerName = complianceInfo.getDeveloperName(); //开发者名称
//                        String privacyUrl = complianceInfo.getPrivacyUrl(); //隐私协议Url
//                        Map<String, String> permissionsMap = complianceInfo.getPermissionsMap(); //权限名称及权限描述列表
//                        String permissionUrl = complianceInfo.getPermissionUrl(); //权限列表url
//                        String functionDescUrl = complianceInfo.getFunctionDescUrl(); //应用功能url
//                    } else {
//                        //非下载类广告
//                    }
                }
            }
        });
    }

    // 广告加载成功后，展示广告
    public void showCacheFeedAd() {
        if (this.mTTFeedAd == null) {
            // Log.i(Const.TAG, "请先加载广告或等待广告加载完毕后再调用show方法");
            loadNativeAd();
            return;
        }
        if (mTTFeedAd.getMediationManager().isReady()) {


            mTTFeedAd.uploadDislikeEvent("mediation_dislike_event");
            /** 5、展示广告 */
            MediationNativeManager manager = mTTFeedAd.getMediationManager();
            if (manager != null) {
                if (manager.isExpress()) { // --- 模板feed流广告
                    mTTFeedAd.setExpressRenderListener(mExpressAdInteractionListener);
                    mTTFeedAd.render(); // 调用render方法进行渲染，在onRenderSuccess中展示广告

                } else {                   // --- 自渲染feed流广告
                    // 自渲染广告返回的是广告素材，开发者自己将其渲染成view
                    View feedView = FeedAdUtils.getFeedAdFromFeedInfo(mTTFeedAd, activity, null, mAdInteractionListener);
                    if (feedView != null) {
                        UIUtils.removeFromParent(feedView);
                        flFeed.removeAllViews();
                        flFeed.addView(feedView);
                    }
                    loadCacheNativeAd();
                }
            }
        }else{
            loadNativeAd();
        }
    }


    //加载信息流广告
    private void loadNativeAd() {
        TTAdNative adNativeLoader = TTAdSdk.getAdManager().createAdNative(activity);
        adNativeLoader.loadFeedAd(buildNativeAdslot(), new TTAdNative.FeedAdListener() {
            @Override
            public void onError(int erroCode, String errorMsg) {
                //广告加载失败
                System.out.println(errorMsg);
            }

            @Override
            public void onFeedAdLoad(List<TTFeedAd> list) {
                //广告加载成功
                //信息流广告渲染具体参考demo
                //如果是自渲染下载类广告可以通过以下api获取下载六要素
                if (list != null && list.size() > 0) {
                    mTTFeedAd = list.get(0);
                    showFeedAd();
//                    ComplianceInfo complianceInfo = mTTFeedAd.getComplianceInfo();
//                    if (complianceInfo != null) {
//                        String appName = complianceInfo.getAppName(); //应用名称
//                        String appVersion = complianceInfo.getAppVersion(); //应用版本号
//                        String developerName = complianceInfo.getDeveloperName(); //开发者名称
//                        String privacyUrl = complianceInfo.getPrivacyUrl(); //隐私协议Url
//                        Map<String, String> permissionsMap = complianceInfo.getPermissionsMap(); //权限名称及权限描述列表
//                        String permissionUrl = complianceInfo.getPermissionUrl(); //权限列表url
//                        String functionDescUrl = complianceInfo.getFunctionDescUrl(); //应用功能url
//                    } else {
//                        //非下载类广告
//                    }
                }
            }
        });
    }

    // 广告加载成功后，展示广告
    private void showFeedAd() {
        if (this.mTTFeedAd == null) {
            // Log.i(Const.TAG, "请先加载广告或等待广告加载完毕后再调用show方法");
            return;
        }
        mTTFeedAd.uploadDislikeEvent("mediation_dislike_event");
        /** 5、展示广告 */
        MediationNativeManager manager = mTTFeedAd.getMediationManager();
        if (manager != null) {
            if (manager.isExpress()) { // --- 模板feed流广告
                mTTFeedAd.setExpressRenderListener(mExpressAdInteractionListener);
                mTTFeedAd.render(); // 调用render方法进行渲染，在onRenderSuccess中展示广告

            } else {                   // --- 自渲染feed流广告
                // 自渲染广告返回的是广告素材，开发者自己将其渲染成view
                View feedView = FeedAdUtils.getFeedAdFromFeedInfo(mTTFeedAd, activity, null, mAdInteractionListener);
                if (feedView != null) {
                    UIUtils.removeFromParent(feedView);
                    flFeed.removeAllViews();
                    flFeed.addView(feedView);
                }
                loadCacheNativeAd();
            }
        }
    }


    private TTNativeAd.AdInteractionListener mAdInteractionListener = new TTNativeAd.AdInteractionListener() {
        @Override

        public void onAdClicked(View view, TTNativeAd ttNativeAd) {
            //Log.d(Const.TAG, "feed click");
        }

        @Override

        public void onAdCreativeClick(View view, TTNativeAd ttNativeAd) {
            // Log.d(Const.TAG, "feed creative click");
        }

        @Override

        public void onAdShow(TTNativeAd ttNativeAd) {
            // Log.d(Const.TAG, "feed show");
        }
    };
    // 模板广告展示监听器
    private MediationExpressRenderListener mExpressAdInteractionListener = new MediationExpressRenderListener() {
        @Override
        public void onRenderFail(View view, String s, int i) {
            //Log.d(Const.TAG, "feed express render fail, errCode: " + i + ", errMsg: " + s);
        }

        @Override
        public void onAdClick() {
            // Log.d(Const.TAG, "feed express click");
        }

        @Override
        public void onAdShow() {
            ///Log.d(Const.TAG, "feed express show");
        }

        @Override
        public void onRenderSuccess(View view, float v, float v1, boolean b) {
            //  Log.d(Const.TAG, "feed express render success");
            if (mTTFeedAd != null) {
                View expressFeedView = mTTFeedAd.getAdView(); // *** 注意不要使用onRenderSuccess参数中的view ***
                UIUtils.removeFromParent(expressFeedView);
                flFeed.removeAllViews();
                flFeed.addView(expressFeedView);
            }
            loadCacheNativeAd();
        }
    };

    public void setFlFeed(FrameLayout flFeed) {
        this.flFeed = flFeed;
    }

    //构造信息流Adslot
    private AdSlot buildNativeAdslot() {
        return new AdSlot.Builder()
                .setCodeId(codeId) //广告位ID
                /**
                 * 注：
                 *  1:单位为px
                 *  2:如果是信息流自渲染广告，设置广告图片期望的图片宽高 ，不能为0
                 *  2:如果是信息流模板广告，宽度设置为希望的宽度，高度设置为0(0为高度选择自适应参数)
                 */
                .setImageAcceptedSize(UIUtils.getScreenWidthInPx(activity), UIUtils.dp2px(activity, 0))
                .setAdCount(3)//请求广告数量为1到3条 （优先采用平台配置的数量）
                .setMediationAdSlot(// 聚合广告请求配置
                        new MediationAdSlot.Builder()
                                .setMuted(true)
                                .build())
                .build();
    }

}
